package com.tz.test.service.impl;

import com.tz.test.entity.ScoreDTO;
import com.tz.test.mapper.TestMapper;
import com.tz.test.service.InsertDataHouseService;
import com.tz.test.vo.TransactionInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class InsertDataHouseServiceImpl extends BaseServer implements InsertDataHouseService<ScoreDTO> {

    @Autowired
    private TestMapper testMapper;

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void saveData(TransactionInfo transactionInfo, List<ScoreDTO> partitionData) throws Exception {
        Exception ex = null;
        try {

            List<ScoreDTO> obj = partitionData.stream()
                    .filter(scoreDTO -> scoreDTO.getStudentAnswer() != null)
                    .collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(obj)) {
                testMapper.batchInsertObj(obj);
            }

            List<ScoreDTO> subj = partitionData.stream()
                    .filter(scoreDTO -> scoreDTO.getStudentAnswer() == null)
                    .collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(subj)) {
                testMapper.batchInsertSubj(subj);
            }
            transactionInfo.getThreadResult().put(Boolean.TRUE);
        } catch (Exception e) {
            log.error("saveData error ", e);
            transactionInfo.getThreadResult().put(Boolean.FALSE);
            ex = e;
        } finally {
            // 执行完成 等待主线程通知回滚
            handleException(transactionInfo, ex);
        }
    }
}
